import { is } from '@electron-toolkit/utils'
import { BrowserWindow, dialog, shell } from 'electron'
import { autoUpdater } from 'electron-updater'
autoUpdater.autoDownload = false
autoUpdater.autoInstallOnAppQuit = false

export default (win: BrowserWindow) => {
  if (!is.dev) autoUpdater.checkForUpdates()
  // Object.defineProperty(app, 'isPackaged', {
  //   get: () => true,
  // })
  // autoUpdater.updateConfigPath = path.join(__dirname, '../../dev-app-update.yml')
  autoUpdater.once('update-available', (_info) => {
    if (process.platform == 'darwin') {
      shell.openExternal(
        'https://apps.apple.com/cn/app/%E8%A3%85%E4%BC%81%E8%B4%A2%E5%A4%9A%E5%A4%9A%E6%A1%8C%E9%9D%A2%E7%AB%AF/id6747324673?mt=12',
      )
    } else {
      dialog
        .showMessageBox({
          type: 'warning',
          title: '更新提示',
          message: '有新版本发布了',
          buttons: ['更新', '取消'],
          cancelId: 1,
        })
        .then((res) => {
          if (res.response == 0) {
            autoUpdater.downloadUpdate()
          }
        })
    }
  })
  autoUpdater.once('update-not-available', (_info: any) => {
    win.webContents.send('version', _info.tag)
  })
  autoUpdater.once('update-downloaded', (_info) => {
    autoUpdater.quitAndInstall()
  })
  autoUpdater.once('error', (_info) => {
    dialog
      .showMessageBox({
        type: 'warning',
        title: '更新提示',
        message: _info.message,
        buttons: ['网站下载', '取消更新'],
        cancelId: 1,
      })
      .then((res) => {
        if (res.response == 0) {
          shell.openExternal('https://app.houdunren.com')
        }
      })
  })
  // 监听下载进度
  autoUpdater.on('download-progress', (progress) => {
    win.webContents.send('downloadProgress', progress)
  })
}
